<template>
  <div class="table-box">
    <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="userApi.getRoles" :pagination="false">
      <template #tableHeader>
        <el-button type="primary" @click="openDialog()">
          <i class="mr-2 fas fa-plus"></i>
          <span>添加角色</span>
        </el-button>
      </template>

      <template #operation="scope">
        <el-button type="danger" link @click="deleteRole(scope.row)">删除</el-button>
      </template>
    </ProTable>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="新增角色" width="500">
      <add-form v-model="rolesForm"></add-form>
      <template #footer>
        <div class="">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import userApi from '@/apis/user';
import AddForm from './form/add.vue';
import type { UserApiType } from '@/apis/user/namespace';
import type { ColumnProps, ProTableInstance } from '@/components/proTable/interface';

// 弹窗状态
const dialogFormVisible = ref(false);
const openDialog = () => {
  dialogFormVisible.value = !dialogFormVisible.value;
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns = reactive<ColumnProps<UserApiType.Roles>[]>([
  { prop: 'id', label: 'ID', width: 80 },
  { prop: 'name', label: 'name' },
  { prop: 'description', label: '描述' },
  { prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'center' },
]);

const rolesForm = ref<Omit<UserApiType.Roles, 'id'>>({
  name: '',
  description: '',
});

// 提交表单
const handleSubmit = async () => {
  await userApi.addRole(rolesForm.value);
  proTable.value?.search();
  dialogFormVisible.value = false;
};

// 删除角色
const deleteRole = (row: UserApiType.Roles) => {
  ElMessageBox.confirm('确认删除该角色吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await userApi.deleteRole({ id: row.id });
    proTable.value?.search();
  });
};
</script>

<style scoped lang="scss"></style>
